<template>
  <div class="page-alert-history">
    <!-- 面包屑 -->
    <Breadcrumb separator=">">
      <BreadcrumbItem to="/home/alert">告警管理</BreadcrumbItem>
      <BreadcrumbItem>告警历史记录</BreadcrumbItem>
    </Breadcrumb>

    <!-- 查询条件 -->
    <div class="search-box">
      <Form :model="searchForm" ref="searchForm" :inline="true" label-position="left">
        <FormItem label="模块" :label-width="40">
          <Select v-model="searchForm.metricId" class="f-w200" placeholder="模块">
            <Option value="全部" key="-1">全部</Option>
            <Option :value="ruleMeta.ruleMetaId" :key="ruleMeta.describe" v-for="ruleMeta in ruleInfo">{{ruleMeta.describe}}</Option>
          </Select>
        </FormItem>
        <FormItem label="节点" :label-width="40">
          <Input v-model="searchForm.hostIp" placeholder="节点"></Input>
        </FormItem>
        <FormItem label="任务名" :label-width="50">
          <Input v-model="searchForm.subJobName" placeholder="任务名"></Input>
        </FormItem>
         <FormItem label="告警状态" :label-width="60">
          <Select v-model="searchForm.recordStatus" class="f-w100" placeholder="告警状态">
            <Option :value="record.value" :key="record.label" v-for="record in RECORD_STATUS">{{record.label}}</Option>
          </Select>
        </FormItem>
        <FormItem label="告警触发时间" :label-width="90">
          <DatePicker type="daterange" v-model="searchForm.alertTime" class="f-w200"></DatePicker>
          <Button type="primary" class="f-w70 f-ml10" @click="getAlertHistoryList">查询</Button>
          <Button type="warning" class="f-w70 f-ml10" @click="clearCondation">重置</Button>
        </FormItem>
      </Form>
    </div>

    <div class="zl-page-loading" v-if="isLoading">
      <Spin fix></Spin>
    </div>
    <div class="history-table" v-else>
      <Table :columns="columns" :data="historyList"></Table>
      <Page :total="pageTotal"
        :current.sync="currentPage"
        :page-size="pageSize"
        :show-total="true"
        :show-sizer="true"
        :show-elevator="true"
        class="page-right"
        @on-change="pageChange"
        @on-page-size-change="pageSizeChange" ></Page>
    </div>
  </div>
</template>
<script type="text/javascript">
import Fetch from '@/api/request'
import { parseTime } from '@/utils'
export default {
  data() {
    return {
      searchForm: {
        metricId: '全部',
        hostIp: '',
        subJobName: '',
        alertTime: ['', ''],
        recordStatus: -1
      },
      FREQUENCYS: [{
        label: '1分钟',
        value: '1m'
      }, {
        label: '5分钟',
        value: '5m'
      }, {
        label: '15分钟',
        value: '15m'
      }, {
        label: '30分钟',
        value: '30m'
      }, {
        label: '1小时',
        value: '1h'
      }, {
        label: '6小时',
        value: '6h'
      }, {
        label: '12小时',
        value: '12h'
      }],
      RECORD_STATUS: [{
        label: '全部',
        value: -1
      }, {
        label: '待接管',
        value: 0
      }, {
        label: '已接管',
        value: 1
      }, {
        label: '已解决',
        value: 2
      }],
      AGGREGATIONES: [{
        label: '平均值',
        value: 'AVG'
      }, {
        label: '最小值',
        value: 'MIN'
      }, {
        label: '最大值',
        value: 'MAX'
      }, {
        label: '求和',
        value: 'SUM'
      }, {
        label: '总数',
        value: 'COUNT'
      }, {
        label: '变化量',
        value: 'STATS'
      }, {
        label: '平均速率',
        value: 'AVGSPEED'
      }],
      ALARM_RULE: [{
        label: '大于',
        value: 'GT'
      }, {
        label: '大于等于',
        value: 'GTE'
      }, {
        label: '小于',
        value: 'LT'
      }, {
        label: '小于等于',
        value: 'LTE'
      }, {
        label: '等于',
        value: 'EQ'
      }, {
        label: '区间',
        value: 'BETWEEN'
      }, {
        label: '空值',
        value: 'NULL'
      }],
      ALERT_LEVEL: [{
        label: '危险',
        value: 'danger'
      }, {
        label: '警告',
        value: 'warning'
      }, {
        label: '普通',
        value: 'ordinary'
      }],
      ruleInfo: [],
      columns: [{
        type: 'index',
        width: 50
      }, {
        title: '模块',
        key: 'metric',
        width: 200
      }, {
        title: '节点',
        key: 'hostIp',
        width: 140
      }, {
        title: '任务名',
        key: 'subJobName',
        width: 150
      }, {
        title: '查询频率',
        width: 80,
        render: (h, params) => {
          let fqLabel = '-'
          for (let i = 0; i < this.FREQUENCYS.length; i++) {
            const fq = this.FREQUENCYS[i]
            if (fq.value === params.row.queryFrequence) {
              fqLabel = fq.label
            }
          }
          return h('span', fqLabel)
        }
      }, {
        title: '聚合方式',
        width: 80,
        render: (h, params) => {
          let aggLabel = '-'
          for (let i = 0; i < this.AGGREGATIONES.length; i++) {
            const agg = this.AGGREGATIONES[i]
            if (agg.value === params.row.aggregationMethod) {
              aggLabel = agg.label
            }
          }
          return h('span', aggLabel)
        }
      }, {
        title: '告警规则',
        width: 80,
        render: (h, params) => {
          let alarmLabel = '-'
          for (let i = 0; i < this.ALARM_RULE.length; i++) {
            const rule = this.ALARM_RULE[i]
            if (rule.value === params.row.ruleEnum) {
              alarmLabel = rule.label
            }
          }
          return h('span', alarmLabel)
        }
      }, {
        title: '阈值',
        width: 50,
        key: 'thresholds'
      }, {
        title: '实际触发值',
        width: 90,
        key: 'actualAlertValue'
      }, {
        title: '告警触发时间',
        width: 160,
        key: 'createTime'
      }, {
        title: '告警状态',
        width: 100,
        fixed: 'right',
        render: (h, params) => {
          if (params.row.recordStatus === 0) {
            return h('Button', {
              props: {
                type: 'primary'
              },
              on: {
                click: () => {
                  this.changeAlertStatus(params.row)
                }
              }
            }, '待接管')
          } else if (params.row.recordStatus === 1) {
            return h('Button', {
              props: {
                type: 'success'
              },
              on: {
                click: () => {
                  this.changeAlertStatus(params.row)
                }
              }
            }, '已接管')
          } else if (params.row.recordStatus === 2) {
            return h('Button', {
              props: {
                type: 'info',
                disabled: true
              }
            }, '已解决')
          }
        }
      }, {
        title: '详细参数',
        key: 'extendParam',
        width: 550
      }],
      historyList: [],
      isLoading: true,
      pageSize: 10,
      currentPage: 1,
      pageSizeList: [10, 20, 30, 50],
      pageTotal: 0,
      pageQuery: false
    }
  },
  mounted() {
    this.getRuleInfo()
    this.getAlertHistoryList()
  },
  methods: {
    // 改变告警状态
    changeAlertStatus(row) {
      Fetch.post({
        url: '/api/scheduler-job/alert/alertRecord/changeStatus',
        params: row
      }).then((res) => {
        this.getAlertHistoryList()
      })
    },
    // 清空
    clearCondation() {
      this.searchForm = {
        metricId: '全部',
        hostIp: '',
        subJobName: '',
        alertTime: ['', ''],
        recordStatus: -1
      }
    },
    // 获取规则信息
    getRuleInfo() {
      Fetch.get({
        url: '/api/scheduler-job/alert/metaInfo'
      }).then((res) => {
        if (res && res.code === '0') {
          this.ruleInfo = res.data
        } else {
          this.$Message.warning({
            content: res.message,
            duration: this.DURATION
          })
        }
      }).catch((err) => {
        this.$Message.error(err.message)
      })
    },
    // 获取告警历史记录列表
    getAlertHistoryList() {
      this.isLoading = true
      let params = {
        page: this.currentPage,
        row: this.pageSize
      }
      let extend = {}
      if (this.searchForm.metricId !== '全部') {
        extend.metricId = this.searchForm.metricId
      }
      if (this.searchForm.hostIp) {
        extend.hostIp = this.searchForm.hostIp
      }
      if (this.searchForm.subJobName) {
        extend.subJobName = this.searchForm.subJobName
      }
      if (this.searchForm.alertTime[0]) {
        extend.startTime = parseTime(this.searchForm.alertTime[0], '{y}-{m}-{d}')
      }
      if (this.searchForm.alertTime[1]) {
        extend.entTime = parseTime(this.searchForm.alertTime[1], '{y}-{m}-{d}')
      }
      if (this.searchForm.recordStatus !== -1) {
        extend.recordStatus = this.searchForm.recordStatus
      }
      if (Object.keys(extend).length !== 0) {
        if (!this.pageQuery) {
          this.currentPage = 1
          params.page = 1
        }
        this.pageQuery = false
        Object.assign(params, {data: decodeURI(JSON.stringify(extend))})
      }

      Fetch.get({
        url: '/api/scheduler-job/alert/alertRecord/get',
        params
      }).then((res) => {
        if (res && res.code === '0') {
          this.historyList = res.data.content
          this.pageTotal = res.data.totalElements
        } else {
          this.$Message.warning({
            content: res.message,
            duration: this.DURATION
          })
        }
        this.isLoading = false
      }).catch((err) => {
        this.isLoading = false
        this.$Message.error(err.message)
      })
    },
    pageChange(page) {
      this.currentPage = page
      this.pageQuery = true
      this.getAlertHistoryList()
    },
    pageSizeChange(size) {
      this.currentPage = 1
      this.pageSize = size
      this.pageQuery = true
      this.getAlertHistoryList()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.search-box {
  padding-top: 30px;
}
.history-table /deep/ {
  th {
    .ivu-table-cell {
      line-height: 14px;
    }
  }
}
</style>
